package com.ncst.mvcweb;

import java.util.ArrayList;

import java.util.List;


// 客户端代码
public class Main {
    public static void main(String[] args) {
        // 创建中介者
        ChatMediator mediator = new ConcreteChatMediator();
        // 创建用户
        User user1 = new ConcreteUser(mediator, "Alice");
        User user2 = new ConcreteUser(mediator, "Bob");
        User user3 = new ConcreteUser(mediator, "Charlie");
        // 将用户添加到中介者中
        mediator.addUser(user1);
        mediator.addUser(user2);
        mediator.addUser(user3);
        // 用户发送消息
        user1.sendMessage("大家好！");
        user2.sendMessage("你好呀，Alice！");
    }
}

// 中介者接口
interface ChatMediator {
    void sendMessage(String message, User user);
    void addUser(User user);
}
// 具体中介者类
class ConcreteChatMediator implements ChatMediator {
    private List<User> users;
    public ConcreteChatMediator() {
        this.users = new ArrayList<>();
    }
    @Override
    public void sendMessage(String message, User user) {
        for (User u : users) {
            if (u != user) {
                u.receiveMessage(message);
            }
        }
    }
    @Override
    public void addUser(User user) {
        this.users.add(user);
    }
}
// 用户接口
interface User {
    void sendMessage(String message);
    void receiveMessage(String message);
}
// 具体用户类
class ConcreteUser implements User {
    private ChatMediator mediator;
    private String name;
    public ConcreteUser(ChatMediator mediator, String name) {
        this.mediator = mediator;
        this.name = name;
    }
    @Override
    public void sendMessage(String message) {
        System.out.println(name + " 发送消息: " + message);
        mediator.sendMessage(message, this);
    }
    @Override
    public void receiveMessage(String message) {
        System.out.println(name + " 收到消息: " + message);
    }
}
